// pages/personal/index.js
import regeneratorRuntime from '../../resource/runtime'
import api from '../../utils/api.js'
import util from '../../utils/util.js'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: app.globalData.userInfo,
        init: false,
        mobile: '', //用户手机
        phone_focus: false,
        smsvcode: '',
        openid: '',
        isHide: true,
        isShow: false,
        tel: '',
        phone: 0,
        phone_input: '',
        isLogin: false,
        code: '',
        code_loading: false,
        code_disabled: false,
        code_focus: false,
        codename: '获取验证码',
        submit_loading: false,
        checked: false,
        isUse: true,
    },

    onChange(event) {
        var that = this;
        this.setData({
            checked: event.detail,
        });
        if (event.detail == true) {
            that.setData({
                isUse: false
            })
        } else {
            that.setData({
                isUse: true
            })
        }
    },
    // getData() {
    // 	// https://dageda.api.hjdz.ltd/user/wechat_check
    // 	let that = this;
    // 	let apis = api.api;
    // 	let url = apis.host + 'user/wechat_check';
    // 	let data = {
    // 		openid: wx.getStorageSync('session').openid
    // 	}
    // 	apis.request(url, data, 'POST').then(function(res) {
    // 		// 返回 102 跳转到注册页面 返回 103跳转到绑定手机号页面 否则返回登录成功信息
    // 		if (res.code == 102) {
    // 			console.log('请先注册', res)
    // 			wx.showToast({
    // 				title: '请先注册',
    // 				icon: 'none'
    // 			})
    // 			setTimeout(function(res) {
    // 				that.setData({
    // 					isShow: true,
    // 					isHide: false,
    // 				})
    // 			}, 2000)
    // 		} else if (res.code == 103) {
    // 			console.log('请绑定手机号', res)
    // 		} else {
    // 			wx.showToast({
    // 				title: '登录成功',
    // 				icon: 'success'
    // 			})
    // 			setTimeout(function(res) {
    // 				wx.navigateTo({
    // 					url: '/pages/index/index'
    // 				})
    // 			}, 2000)
    // 		}
    // 	}).catch(function(res) {
    // 		console.log('登录失败', res)
    // 	})
    // },
    /**
     * 生命周期函数--监听页面加载
     */

    onLoad: function (options) {
        // that.getData()
        var that = this
        let time = new Date();
        let createTime = wx.getStorageSync('createTime');
        let token = wx.getStorageSync('token');
        let isLogin = app.globalData.isLogin;
        if (!token) {
            wx.login({
                success: res => {
                    that.setData({
                        code: res.code
                    })
                    let apis = api.api;
                    let url = apis.host + "user/wechat_decode";
                    let data = {
                        code: res.code
                    };
                    apis.request(url, data, "POST").then(function (res) {
                        // console.log(res)
                        let session = res.data
                        wx.setStorageSync('session', session)
                        // console.log('1111', wx.getStorageSync('openid'))
                    })
                    // console.log('1111', wx.getStorageSync('openid'))
                }
            })

        } else if (time - createTime > 14 * 24 * 3600 * 1000) {
            let token = wx.getStorageSync('token');
            wx.request({
                url: wx.getStorageSync('config').refresh_url,
                method: 'post',
                data: {
                    token: token.access_token
                },
                success(res) {
                    if (res.data.code == 200) {
                        let token = res.data.data;
                        wx.setStorageSync('token', token); //存储token
                        let createTime = new Date();
                        wx.setStorageSync('createTime', createTime);
                    }
                }
            })

        } else {
            // console.log("app中登录了，token有效")
        }
    },
    goDj() {
        wx.navigateTo({
            url: '/pages/serAgreement/serAgreement'
        })
    },
    getPhoneNumber: function (e) {
        var that = this
        var loc = wx.getStorageSync('myLocal')
        if (that.data.checked == true) {
            let apis = api.api;
            let mobileUrl = apis.host + 'user/wechat_decode_pass';
            let encryptedData = e.detail.encryptedData.toString();
            let iv = e.detail.iv.toString();
            let mobileData = {
                encryptedData: encryptedData,
                iv: iv,
                sessionKey: wx.getStorageSync('session').session_key
            }
            apis.request(mobileUrl, mobileData, 'POST').then(function (res) {
                that.setData({
                    phone: res.data.phoneNumber
                })
                if (res.data.phoneNumber) {
                    let apis = api.api;
                    let url = apis.host + 'user/wechat_check';
                    if (!loc) {
                        wx.getLocation({
                            type: 'gcj02',
                            success(locRes) {
                                let data = {
                                    openid: wx.getStorageSync('session').openid,
                                    phone: res.data.phoneNumber,
                                    lat: locRes.latitude,
                                    /* 是	string	经度 */
                                    lng: locRes.longitude,
                                    /* 是	string	纬度 */
                                    area_code: loc.area_code ? loc.area_code : '',
                                    /* 否	string	微信用户ID */
                                    recommend: app.getRecommon(),
                                    /* 否	string	推荐码 */
                                    reType: app.getRecommonType(),
                                }
                                apis.request(url, data, 'POST').then(function (res) {
                                    if (res.data.token) {
                                        wx.setStorageSync('token', res.data.token)
                                        // app.globalData.isLogin = true;
                                        wx.setStorageSync('isLogin', true)
                                    } else {
                                        // console.log('获取token失败', res.data.token)
                                    }
                                    // console.log('1111', res)
                                    // if (res.code == 200) {
                                    // 	wx.navigateTo({
                                    // 		url: '/pages/index/index'
                                    // 	})
                                    // }
                                    if (res.code == 102) {
                                        // console.log('请先注册', res)
                                        wx.showToast({
                                            title: '请先注册',
                                            icon: 'none'
                                        })
                                        that.setData({
                                            isShow: true,
                                            isHide: false,
                                        })
                                    } else if (res.code == 103) {
                                        // console.log('请绑定手机号', res)
                                    } else {
                                        wx.showToast({
                                            title: '登录成功',
                                            icon: 'success'
                                        })
                                        app.initUser();
                                        setTimeout(function (res) {
                                            wx.navigateBack()
                                        }, 2000)
                                    }
                                }).catch(function (res) {
                                    if (res.code == 102) {
                                        // console.log('请先注册', res)
                                        wx.showToast({
                                            title: '请先注册',
                                            icon: 'none'
                                        })
                                        setTimeout(function (res) {
                                            that.setData({
                                                isShow: true,
                                                isHide: false,
                                            })
                                        }, 2000)
                                    }
                                })
                            }
                        })
                    }
                }
            })
        } else {
            wx.showToast({
                title: '请先同意代驾条例',
                icon: 'none'
            })
        }
    },
    phoneInput({
        detail
    }) {
        let phone_input = detail.value
        this.setData({
            phone_input
        })
    },

    // 微信一键登录
    async loginOnce(e) {
        var that = this
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: function (res) {
                this.setData({
                    userInfo: res.userInfo
                })
            },
            fail: function (res) {
                wx.showModal({
                    title: '警告',
                    content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
                    showCancel: false,
                    confirmText: '返回授权',
                    success: function (res) {
                        // 用户没有授权成功，不需要改变 isHide 的值
                        if (res.confirm) {}
                    }
                });
            }
        })
    },
    //注册登录
    async login() {
        var that = this
        let apis = api.api;
        let url = apis.host + 'user/wechat_login'
        let data = {
            openid: wx.getStorageSync('session').openid
        }
        apis.request(url, data, 'POST').then(function (res) {}).catch(function (res) {
            that.setData({
                isLogin: true,
                isShow: false
            })
        })
    },

    codeInput({
        detail
    }) {
        let code = detail.value
        this.setData({
            code
        })
    },
    inputvalue: function (e) {
        // console.log(e)
        this.setData({
            mobile: e.detail.value
        })
    },
    checkinput: function (e) {
        this.setData({
            smsvcode: e.detail.value
        })
    },
    getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        var that = this;
        var loc = wx.getStorageSync('myLocal')
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                wx.setStorageSync('userInfo', res.userInfo)
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
                var mobile = that.data.mobile;
                if (mobile == '') {
                    mobile = that.data.phone
                } else {
                    mobile = mobile
                }
                if ((/^1(3|4|5|6|7|8|9)\d{9}$/.test(mobile)) && (/[0-9]{4}/.test(that.data
                        .smsvcode))) {
                    var apis = api.api
                    const url = apis.host + "user/reg";
                    if (!loc) {
                        wx.getLocation({
                            type: 'gcj02',
                            success(res) {
                                const data = {
                                    phone: mobile,
                                    /* 是	string	手机号 */
                                    code: that.data.smsvcode,
                                    /* 是	string	手机验证码 */
                                    lat: res.latitude,
                                    /* 是	string	经度 */
                                    lng: res.longitude,
                                    /* 是	string	纬度 */
                                    area_code: loc.area_code ? loc.area_code : '',
                                    /*, 是	string	城市区域编码 */
                                    openid: wx.getStorageSync('session').openid,
                                    /* 否	string	微信用户ID */
                                    recommend: app.getRecommon(),
                                    /* 否	string	推荐码 */
                                    reType: app.getRecommonType(),
                                    username: res.userInfo.nickName,
                                    /* 否	string	用户名，微信用户必填 */
                                    avatar: res.userInfo.avatarUrl /*, 否	string	用户头像 */
                                };
                                apis.request(url, data, "POST").then(function (res) {
                                    app.globalData.phone = that.data.mobile
                                    wx.showToast({
                                        title: '注册成功!',
                                        icon: 'success',
                                        duration: 2000
                                    })
                                    let url = apis.host + "user/wechat_check"
                                    let data = {
                                        openid: wx.getStorageSync('session').openid,
                                    }
                                    apis.request(url, data, "POST").then(function (res) {
                                        // console.log('登录成功了', res)
                                        if (res.code == 200) {
                                            wx.setStorageSync('token', res.data
                                                .token); //存储token
                                            // app.globalData.isLogin = true;
                                            wx.setStorageSync('isLogin', true);
                                            // console.log('token', apis.token)
                                            app.initUser();
                                            wx.navigateTo({
                                                url: '/pages/index/index',
                                            })
                                        } else {
                                            let msg = res.msg
                                            wx.showToast({
                                                title: msg,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }).catch(function (res) {
                                        // console.log('失败', res)
                                    })
                                }).catch(function (res) {
                                    // console.log('fail', res)
                                })
                            }
                        })
                    }
                } else if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(mobile))) {
                    wx.showToast({
                        title: '手机号码错误!',
                        icon: 'error',
                        duration: 2000
                    })
                } else {
                    wx.showToast({
                        title: '验证码有误!',
                        icon: 'error',
                        duration: 2000
                    })

                }
            }
        })
    },
    putlogin: function () {
        const that = this;
        that.getUserProfile();
    },
    getcheck: function (e) {
        let that = this;
        // console.log(that.data.mobile)
        var mobile = that.data.mobile
        if (mobile == '') {
            mobile = that.data.phone
        } else {
            mobile = mobile
        }
        var num = 60,
            timer;
        if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(mobile))) {
            wx.showToast({
                title: '手机号不正确',
                icon: 'error',
                duration: 2000
            })
        } else {
            that.setData({
                codenum: num
            })
            wx.showToast({
                title: '获取验证码',
                icon: 'loading',
                duration: 3000
            })
            let apis = api.api;
            let url = apis.host + '/sys/sendmsg';
            let data = {
                phone: mobile
            };
            apis.request(url, data, 'POST').then(function (res) {
                // console.log(res)
                timer = setInterval(function () {
                    num--;
                    if (num <= 0) {
                        clearInterval(timer);
                        that.setData({
                            codename: '重新发送',
                            disable: false,
                        })
                    } else {
                        that.setData({
                            codename: num + 's',
                            disable: true
                        })

                    }
                }, 800)
            })
        }
    },
})